#!/usr/bin/node 

var fs = require("fs"); 
var JSON = require("JSON"); 

function po2json(buffer, options) {
	// Setup options and load in defaults
	options = options || {};
	var defaults = {
		pretty: false,
		fuzzy: false,
		stringify: false,
		format: 'raw',
		domain: 'messages',
		charset: 'utf8'
	};

	for (var property in defaults) {
		options[property] = 'undefined' !== typeof options[property] ? options[property] : defaults[property];
	}

	// Parse the PO file
	var parsed = require('gettext-parser').po.parse( buffer, defaults.charset );

	// Create gettext/Jed compatible JSON from parsed data
	var result = {},
			contexts = parsed.translations;

	Object.keys(contexts).forEach(function (context) {
		var translations = parsed.translations[context];

		Object.keys(translations).forEach(function (key, i) {
			var t = translations[key],
					translationKey = context.length ? context + '\u0004' + key : key,
					fuzzy = t.comments && t.comments.flag && t.comments.flag.match(/fuzzy/) !== null;

			if (!fuzzy || options.fuzzy) {
				if (options.format === 'mf') {
					result[translationKey] = t.msgstr[0];
				} else {
					result[translationKey] = [ t.msgid_plural ? t.msgid_plural : null ].concat(t.msgstr);
				}
			}

			// In the case of fuzzy or empty messages, use msgid(/msgid_plural)
			if (options['fallback-to-msgid'] && (fuzzy && !options.fuzzy || t.msgstr[0] === '')) {
				if (options.format === 'mf') {
					result[translationKey] = key;
				} else {
					result[translationKey] = [ t.msgid_plural ? t.msgid_plural : null ]
							.concat(t.msgid_plural ? [key, t.msgid_plural] : [key]);
				}
			}

		});
	});

	// Attach headers (overwrites any empty translation keys that may have somehow gotten in)
	result[''] = parsed.headers;

	if (options.format === 'mf') {
		delete result[''];
	}

	// Make JSON fully Jed-compatible
	if (options.format.indexOf('jed') === 0) {
		var jed = {
			domain: options.domain,
			locale_data: {}
		};
		if (options.format === 'jed1.x'){
			for (key in result) {
				if (result.hasOwnProperty(key) && key !== ''){
					result[key].shift();
				}
			}
		}
		jed.locale_data[options.domain] = result;
		jed.locale_data[options.domain][''] = {
			domain: options.domain,
			plural_forms: result['']['plural-forms'],
			lang: result['']['language']
		};

		result = jed;
	}

	return options.stringify ? JSON.stringify( result, null, options.pretty ? '	 ' : null ) : result;
}

var result = {}; 

if(process.argv.length < 3) {
	console.error("usage: po2js <files...>"); 
	process.exit(1); 
}

for(var i = 2; i < process.argv.length; i++){
	var potext = fs.readFileSync(process.argv[i]); 
	var json = po2json(potext);

	var meta = json[""]; 
	var tbl = {}; 
	if(meta instanceof Object){
		result[meta["language"]] = tbl; 
	} else {
		console.error("Missing po header!"); 
		process.exit(1); 
	}

	Object.keys(json).map(function(k){
		if(k == "") return; 
		var line = json[k]; 
		
		if(tbl != null && line.length == 2){
			tbl[k] = line[1]; 
		}
	}); 
}

// output as juci javascript 
console.log("angular.module('gettext').run(['gettextCatalog', function (gettextCatalog) {"); 
Object.keys(result).map(function(k){
	console.log("\tgettextCatalog.setStrings('"+k+"', "+JSON.stringify(result[k])+");"); 
}); 
console.log("}]);"); 
 
